package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduTeacher;
import com.atguigu.eduservice.entity.vo.TeacherQuery;
import com.atguigu.eduservice.service.EduTeacherService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2022-05-11
 */
@Api(description = "讲师管理")
@RestController
@RequestMapping("/eduservice/teacher")
@CrossOrigin
public class EduTeacherController {

    @Autowired
    private EduTeacherService teacherService;

    @ApiOperation(value = "所有讲师列表")
    @GetMapping("/findAll")
    public R findAll(){
        List<EduTeacher> list = teacherService.list(null);
        return R.ok().data("items",list);
    }

    @ApiOperation(value = "逻辑删除讲师")
    @DeleteMapping("{id}")
    public R removeTeacher(@PathVariable String id){
        boolean flag=teacherService.removeById(id);
        return flag?R.ok():R.error();
    }

    /**
     * 讲师分页查询
     * @param page 页数
     * @param limit 每页条数
     * */
    @ApiOperation(value = "讲师分页查询")
    @GetMapping("{page}/{limit}")
    public R pageList(@PathVariable Long page,
                      @PathVariable Long limit){

        Page<EduTeacher> pageTeacher = new Page<>(page,limit);
        //调用方法实现分页，底层封装，把分页所有数据封装到pageTeacher对象里面
        teacherService.page(pageTeacher,null);
        long total=pageTeacher.getTotal();//总记录数
        List<EduTeacher> records = pageTeacher.getRecords();//数据list集合

        //data()方法会将键值对放入map中，返回值是R，所有可以连点（链式编程）
        return R.ok().data("total",total).data("rows",records);
    }

    /**
     * 条件查询带分页的方法
     * */
    @PostMapping("pageTeacherCondition/{page}/{limit}")
    public R pageTeacherCondition(@PathVariable long page, @PathVariable long limit,
                                  @RequestBody(required = false) TeacherQuery teacherQuery){    //@RequestBody 参数使用json格式，required=false 参数可以为空。@RequestBody不能使用get请求

        /**异常测试*/
//        try {
//            int r=19/0;
//        } catch (Exception e) {
////            e.printStackTrace();
//            throw new GuliException(20001,"执行了自定义异常处理。。。");
//        }

        //创建page对象
        Page<EduTeacher> pageTeacher = new Page<>(page,limit);
        //构建条件
        QueryWrapper<EduTeacher> wrapper =new QueryWrapper<>();
        //多条件动态组合查询
        String name=teacherQuery.getName();
        Integer level=teacherQuery.getLevel();
        String begin=teacherQuery.getBegin();
        String end=teacherQuery.getEnd();
        //构建条件
        if (!StringUtils.isEmpty(name)){//判断name是否为空
            wrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(level)){
            wrapper.eq("level",level);//eq 等于
        }
        if (!StringUtils.isEmpty(begin)){
            wrapper.ge("gmt_create",begin);//ge 大于等于
        }
        if (!StringUtils.isEmpty(end)){
            wrapper.le("gmt_modified",end);//le 小于等于
        }

        //排序 根据创建时间降序
        wrapper.orderByDesc("gmt_create");

        //调用方法实现分页，底层封装，把分页所有数据封装到pageTeacher对象里面，wrapper为条件
        teacherService.page(pageTeacher,wrapper);

        long total=pageTeacher.getTotal();//总记录数
        List<EduTeacher> records = pageTeacher.getRecords();//数据list集合

        //data()方法会将键值对放入map中，返回值是R，所有可以连点（链式编程）
        return R.ok().data("total",total).data("rows",records);
    }

    /**
     * 添加讲师
     * */
    @PostMapping("addTeacher")
    public R addTeacher(@RequestBody EduTeacher eduTeacher){
        boolean save = teacherService.save(eduTeacher);
        return save?R.ok():R.error();
    }

    /**
     * 根据讲师id进行查询
     * */
    @GetMapping("getTeacher/{id}")
    public R getTeacher(@PathVariable String id){
        EduTeacher eduTeacher = teacherService.getById(id);
        return R.ok().data("teacher",eduTeacher);
    }

    /**
     * 修改讲师
     * */
    @PostMapping("updateTeacher")
    public R updateTeacher(@RequestBody EduTeacher eduTeacher){
        boolean flag = teacherService.updateById(eduTeacher);
        return flag?R.ok():R.error();
    }

}

